package com.liming.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liming.server.domain.File;
import com.liming.server.domain.FileExample;
import com.liming.server.dto.FileDto;
import com.liming.server.dto.PageDto;
import com.liming.server.mapper.FileMapper;
import com.liming.server.util.CopyUtil;
import com.liming.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FileService {
    @Resource
    private FileMapper fileMapper;

    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        FileExample fileExample = new FileExample();
        List<File> fileList = fileMapper.selectByExample(fileExample);
        PageInfo<File> pageInfo = new PageInfo<>(fileList);
        pageDto.setTotal(pageInfo.getTotal());
        //将fileList通过CopyUtil.copyList()方法复制给fileDtoList
        List<FileDto> fileDtoList =CopyUtil.copyList(fileList,FileDto.class);
        pageDto.setList(fileDtoList);
    }

    public void save(FileDto fileDto){
        //将fileDto通过CopyUtil.copy()方法复制给File
        File file = CopyUtil.copy(fileDto, File.class);
        File fileDb = selectByKey(fileDto.getKey());
        if(fileDb == null){
            this.insert(file);
        }else{
            fileDb.setShardIndex(fileDto.getShardIndex());
            this.update(fileDb);
        }
    }

    private void insert(File file){
        Date now = new Date();

        file.setCreatedAt(now);
        file.setUpdatedAt(now);
        file.setId(UuidUtil.getShortUuid());
        fileMapper.insert(file);
    }
    private void update(File file){
        file.setUpdatedAt(new Date());
        fileMapper.updateByPrimaryKey(file);
    }
    public void delete(String id){
        fileMapper.deleteByPrimaryKey(id);
    }

    public File selectByKey(String key){
        FileExample example = new FileExample();
        example.createCriteria().andKeyEqualTo(key);
        List<File> fileList = fileMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(fileList)){
            return null;
        }else{
            return fileList.get(0);
        }
    }

    /**
     * 根据文件标识查询数据库记录
     */
    public FileDto findByKey(String key){
        return CopyUtil.copy(selectByKey(key),FileDto.class);
    }
}